<template>
    <el-dialog v-model="visible" :title="title" :width="width" :key="version">
        <div class="psc-main-popup-table" style="padding: 0px">
            <div class="left" style="height: 400px">
                <div class="waiting waiting-search-flex" v-if="searchType === 'select'">
                    <el-button type="text" v-if="selectType === 'checkbox'"
                               @click="handleAll" style="margin-right: 10px">全选当前</el-button>
                    <el-input v-if="formLayout" v-model="searchValue" @keyup.enter="handleSearch"
                              :placeholder="formLayout.length === 1 ? formLayout[0].placeholder : '请输入搜索关健字'"
                    >
                        <template #prepend v-if="formLayout && formLayout.length >= 2">
                            <el-select   v-model="searchKey" style="width:100px;">
                                <el-option  v-for="item in formLayout"
                                            :key="item.prop" :label="item.placeholder"
                                            :value="item.prop"></el-option>
                            </el-select>
                        </template>
                    </el-input>
                    <el-button type="primary" style="margin-left: 10px" @click="handleSearch">搜索</el-button>
                </div>

                <div class="waiting waiting-search-flex" v-else>
                    <el-button type="text" v-if="selectType === 'checkbox'"
                               @click="handleAll" >全选当前</el-button>

                    <template v-if="formLayout" v-for="sub in formLayout">
                        <el-input   v-model="searchParams[sub.value]"  class="psc-select-max-input"
                                    @keyup.enter="handleSearch"
                                    :placeholder="sub.placeholder"
                        >
                        
                        </el-input>
                    </template>
                    
                    <el-button type="primary" style="margin-left: 10px" @click="handleSearch">搜索</el-button>
                </div>
                <div height="356px"  v-if="visible">
                    <vxe-table class="psc-more-table-staff" :show-overflow="false"  :data="list" height="356" @cell-dblclick="handleDbclick"  @scroll="handleScroll" width="100%" @cell-click="handleSelectRow">
                        <vxe-column >
                            <template  #default="{ row }">
                                <div class="forbid-bg"></div>
                                <el-checkbox v-if="selectType === 'checkbox'" :key="row[modelKey]" v-model="checkboxItems[row[modelKey]]"></el-checkbox>
                                <el-radio v-else v-model="value"  :key="row[modelKey]" :label="row[modelKey]"> &nbsp;</el-radio>
                            </template>
                        </vxe-column>
                        <vxe-column     :min-width="item.minWidth"
                                        :title="item.label"
                                        v-for="item in columns"
                                        :key="item.prop"
                                        :field="item.prop"
                        ></vxe-column>
                    </vxe-table>
                </div>
            </div>
            <div class="right" style="height: 400px" v-if="selectType === 'checkbox'">
                <div class="waiting waiting-flex">
                    <div>已选： <span>{{selected.length}}</span>项</div>
                    <el-button type="text" @click="handleClearAll">清空</el-button>
                </div>
                <div height="356px" v-if="visible">
                    <vxe-table :show-overflow="false"  class="psc-more-table-staff" :data="selected" height="356"  width="100%">
                        <vxe-column     :minWidth="item.minWidth"
                                        :title="item.label" v-for="item in selectedColumns"
                                        :key="item.prop"
                                        :field="item.prop"
                        ></vxe-column>
                        <vxe-column  width="30px">
                            <template #default="{row, rowIndex}">
                                <el-icon    class="close-visible" @click="handleDel(row, rowIndex)"
                                            :size="16" color="#999"><close /></el-icon>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="footer-flex">
                <div class="footer-align-left"></div>
                <div class="footer-align-right">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="handleSure"  :disabled="disabledBtn">确定</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, defineProps, computed } from 'vue';
import {  MdCheckbox, MdTable, MdTableColumn, MdDialog,
    MdButton, MdIcon, MdMessage, MdRadio,
    MdSelect, MdOption, MdInput, MdScrollbar, MdInfiniteScroll as VInfiniteScroll} from 'mdesign3';
import { Close } from '@mdesign3/icons-vue';
import request  from '@/utils/http';
import { VxeTable, VxeColumn } from 'vxe-table';
// 定义Props的值
defineProps({
    labelWidth: {
        type: String,
        default: '',
    },
    rules: {
        type: Object,
        default: () => {
            return {};
        },
    },
    modelValue: {
        type: Object,
        default: () => {
            return {};
        },
    },
    
});
const visible = ref(false);
const params = ref({
    pageNo: 1,
    pageSize: 20,
});



const total = ref(0);
const form = ref();
const list =  ref([]);
const cacheList = ref([]);
const formLayout = ref([]);
const columns = ref([]);
const selectedColumns = ref([]);
const loading = ref(false);
const width = ref('700px');
const title = ref('');
const selectType = ref('radio');
const value = ref('');
const modelKey = ref('radioId');
let url = '';
let modelValueText = [];
let modelText = '';
const checkboxItems = ref({}); // 多选项、
const selected = ref([]); // 已选
const searchKey = ref(''); // 搜索的字段
const searchValue = ref(''); // 搜索的值
const searchParams = ref({}); // 搜索的参数
const searchType = ref('select'); // 搜索的类型
const version = ref(0);
const disabledPage = ref(false)
let reback;
let dataDict = {};
let method = 'post';

const selectIndex = computed(() => {
    const res = {};
    selected.value.forEach((element, index) => {
        res[element[modelKey.value]] = index;
    });
    return res;
});

function changeDict() {
    const res = {};
    list.value.forEach(item => {
        res[item[modelKey.value]] = item;
    });
    dataDict = res;
}

let modelValueArr = [];
function modelValueInit() {
    selected.value = [];

    if (selectType.value === 'radio' && value.value) {
        if (dataDict[value.value]) {
            selected.value.push(dataDict[value.value]);
        } else {
            selected.value.push({
                [modelKey.value]: value.value,
                [modelText]: modelValueText,
            });
        }
        return;
    }
    modelValueArr.forEach((item, index) => {
        checkboxItems.value[item] = true;
        if (dataDict[item]) {
            selected.value.push(dataDict[item]);
        } else {
            selected.value.push({
                [modelKey.value]: item,
                [modelText]: modelValueText[index],
            });
        }
    });
}


// 禁止定击确定的条件
const disabledBtn = computed(() => {
    if (selectType.value === 'radio' && !selected.value.length) {
        return true;
    }
    if (selectType.value === 'checkbox' && selected.value.length <= 0) {
        return true;
    }
    return false;
});

// 可选择数量
const canSelectNum = computed(() => {
    let num = 0;
    list.value.forEach(item => {
        if (!item.disabled) {
            num++;
        }
    });
    return num;
});


function handleAll(val) {
    const res = {};

    list.value.forEach(element => {
        res[element[modelKey.value]] = true;
    });
    checkboxItems.value = res;
    selected.value = list.value;
}



let isInit = true;
async function getList() {
    if (loading.value) {
        return;
    }
    loading.value = true;
    let data = {
        url: url,
        method: 'post',
        data: {
            pageNo: params.value.pageNo,
            pageSize: params.value.pageSize,
            param: {
                ...params.value.param,
                [searchKey.value]: searchValue.value,
                ...searchParams.value,
            },
        },
    };

    if (method === 'GET') {
        data = {
            url: url,
            method: 'get',
            params: {
                pageNo: params.value.pageNo,
                pageSize: params.value.pageSize,
                ...params.value.param,
                ...searchValue.value,
                [searchKey.value]: searchValue.value,
                ...searchParams.value,
            },
        };
    }


    if (disabledPage.value) {
        data = {
            url: url,
            method: 'post',
            data: {
                ...params.value.param,
            },
        };
    }

    try {
        const res = await request(data);
        if (parseInt(res.code) === 0 && !disabledPage.value) {
            afterEachList && afterEachList(res.data.list);
            if ( params.value.pageNo === 1) {
                list.value = res.data.list;
            } else {
                list.value = list.value.concat(res.data.list);
            }

            total.value = res.data.totalCount;
            changeDict();
            isInit && modelValueInit();
            isInit = false;
            params.value.pageNo++;
        }

        if (parseInt(res.code) === 0 && disabledPage.value) {
            afterEachList && afterEachList(res.data);
            list.value = res.data;
            cacheList.value = res.data;
            changeDict();
            isInit && modelValueInit();
        }
    } catch (error) {
        MdMessage(error);
    }
    loading.value = false;
}


function handleSelectRow({row}) {
    if (row.disabled) return;
    if (selectType.value === 'checkbox') {
        const exist = checkboxItems.value[row[modelKey.value]];
        if (exist) {
            checkboxItems.value[row[modelKey.value]] = false;
            selected.value.splice(selectIndex.value[row[modelKey.value]], 1);
            return;
        }
        checkboxItems.value[row[modelKey.value]] = true;
        selected.value.push(dataDict[row[modelKey.value]]);
        return;
    }

    value.value = row[modelKey.value];
    modelValueText = row[modelText];
    selected.value = [row];
}

function handleDel(row, index) {
    if (selectType.value === 'radio') {
        value.value = value;
        modelValueText = '';
    };
    checkboxItems.value[row[modelKey.value]] = false;
    selected.value.splice(index, 1);
}

function handleSure() {
    reback(selected.value);
    close();
    visible.value = false;
}

function handleClearAll() {
    checkboxItems.value = {};
    selected.value = [];
    value.value = '';
    modelValueText = '';
}



function handleLoad() {
    if (params.value.pageNo > 1 && list.value.length >= total.value) {
        return;
    }
    getList();
}

function handleScroll(e) {
    if(disabledPage.value) return;
    if (e.scrollTop >  e.scrollHeight - 600) {
        handleLoad();
    }
}





let afterEachList;
// 导出的方法
function show(options, callback) {
    afterEachList = options.afterEachList || null;
    value.value = '';
    checkboxItems.value = {};
    visible.value = true;
    title.value = options.title;
    columns.value = options.columns || [];
    selectedColumns.value = options.selectedColumns || options.columns;
    formLayout.value = options.formLayout || []; // 搜索框配置
    modelText = options.modelText || ''; //选择中的健值
    searchType.value = options.searchType || 'select'; // 搜索框类型 select  其它多个框
    modelValueText = options.modelValueText || [];
    disabledPage.value = options.disabledPage || false; // 是否禁用分页
    method = options.method || 'POST';
    if (options.formLayout) {
        searchKey.value = options.formLayout[0].prop;
    } else {
        searchKey.value = '';
    }
    width.value = options.width || '800px';
    url = options.url;
    params.value.param = options.params || {};
    params.value.pageNo = 1;
    params.value.pageSize = 20;
    modelKey.value = options.modelKey || 'radioId'; // 选中主键
    selectType.value = options.selectType;
    list.value = [];
    selected.value = [];
    reback = callback; // 回调函数
    isInit = true;
    modelValueArr = options.modelValue || [];
    value.value = options.modelValue;
    searchValue.value = null;
    version.value++;
    getList();
}
function handleSearch() {
    list.value = []
    if (disabledPage.value) {
        if (searchType.value === 'select' && searchValue.value) {
            cacheList.value.forEach(item => {
                item[searchKey.value] && item[searchKey.value].indexOf(searchValue.value) > -1 && list.value.push(item);
            })
            return;
        } 

        if (searchType.value === 'select' && !searchValue.value) {
            list.value = cacheList.value;
            return;
        } 
        
        if (searchType.value !== 'select') {
            const keyTexts = formLayout.value.map(item => item.value);
           
            cacheList.value.forEach(item => {
                let i = 0;
                keyTexts.forEach(keyText => {
                    if(searchParams.value[keyText] && item[keyText].indexOf(searchParams.value[keyText]) > -1) {
                        i++;
                    }
                    if(!searchParams.value[keyText]) {
                        i++;
                    }
                })

                if(i === keyTexts.length) {
                    list.value.push(item);
                }
            })
            return;
        } 
    }   
    params.value.pageNo = 1;
    getList();
}
function handleClose() {
    visible.value = false;
}
function handleDbclick() {
    if (selectType.value === 'radio') {
        handleSure();
    }
}

defineExpose({
    show,
    handleClose,
});


</script>
<style lang="less" setup>
.forbid-bg {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    z-index: 3;
}
.checkbox-table {
    position: relative;
    z-index: 0;
}

.is-checked .el-checkbox__inner {
    background-color: var(--el-checkbox-checked-bg-color);
    border-color: var(--el-checkbox-checked-input-border-color);
    &::after {
        color: #fff;
        transform: rotate(45deg) scaleY(1);
    }
}


.psc-main-popup-table {
    display:flex;
    .left,.right {
        flex: 1;
        overflow: hidden;
    }
    .left{
        flex: 3,
    }
    .right {
        flex: 2
    }
}
.el-table td.el-table__cell {
    
}

.waiting {
    height: 44px;
    background-color:#f1f1f1;
    line-height: 40px;
    padding: 0px 10px;

}
.waiting-flex {
    display: flex;
    align-items: center;
    justify-content:space-between;
}
.psc-main-popup-table {
    .left {
        border-right: #ddd solid 1px;
    }
}
.waiting-search-flex {
    display: flex;
    align-items:center;
    /deep/ .el-input-group__prepend {
        height: 24px;
    }
}
.close-visible {
    width: 24px;
    height: 20px;
    cursor: pointer;
}
.loading-text {
    text-align: center;
    color: #999;
}

.psc-more-table {
    thead {
        display: none;
    }
    .vxe-body--column, .vxe-body--column:not(.col--ellipsis) {
        padding: 5px 0px !important;
    }
    .vxe-body--column {
        height: auto !important;
        color: #333 !important;
        font-size: 12px;
    }
    .vxe-table--body-wrapper {
        overflow-x: hidden;
    }
}

.psc-select-max-input {
    width: 150px;
    margin-left: 10px;
}
</style>
